#include "cgic.h"
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include "session.h"
#include "cgi_interface.h"
#include "global_val.h"

// 接口参数：
// 1.dev_mac
// 2.method
// 3.如果是SET就需要另一个参数beep_status
// 

char *success_json="{\"STATUS\":\"SUCCESS\"}";
char *success_json2="{\"STATUS\":\"SUCCESS\",\"BEEP_STATUS\":\"%s\"}";
char *faild_json="{\"STATUS\":\"FAIL\",\"ERROR\":\"%s\"}";
void error_printf(cgiFormResultType ret,char *str,char* out);
int cgiMain() {
	
	char dev_mac[256];
	int beep_status;
	int ret;
	char json_data[256];
	char method[4];
	char token[18];
	char out[1024];
	
	//这里为了能够跨域还要能带COOKIE 做点操作
	fprintf(cgiOut,"Access-Control-Allow-Credentials: true\r\n");
	if(cgiOrigin){
		sprintf(out,"Access-Control-Allow-Origin: %s\r\n",cgiOrigin);
		fprintf(cgiOut,out); 
	}else{
		fprintf(cgiOut,"Access-Control-Allow-Origin: *\r\n");
	}
	
	
	cgiHeaderContentType("text/html");
	
	ret = cgiCookieString("token", token,17);//获取用户的token
	if(ret!=cgiFormSuccess){
		//token有问题小老弟 没有从cookie中获取到token
		//试试其他方法获取
		ret = cgiFormString("token", token, 17);
		if(ret!=cgiFormSuccess){
			// 两种方法都没获取到
			fprintf(cgiOut,"{\"STATUS\":\"FAIL\",\"ERROR\":\"No Login\"}");
			return 0;
		}
		
	}
	
	
	if(!has_session(token)){
		//没登录就想访问
		fprintf(cgiOut,"{\"STATUS\":\"FAIL\",\"ERROR\":\"No Login\"}");
		return 0;
	}
	
	ret = cgiFormString("dev_mac",dev_mac,256);  //判断methon是否有提交
	if(ret!=cgiFormSuccess){
		error_printf(ret,"dev_mac",json_data);
		fprintf(cgiOut,json_data);
		return 0;
	}
	
	ret = cgiFormString("method",&method,4);  //判断methon是否有提交
	if(ret!=cgiFormSuccess){
		error_printf(ret,"method",json_data);
		fprintf(cgiOut,json_data);
		return 0;
	}
	
	if(strcmp(method,"SET")==0){ //SET
		ret = cgiFormInteger("beep_status", &beep_status, -1);
		if(ret!=cgiFormSuccess){
			error_printf(ret,"beep_status",json_data);
			fprintf(cgiOut,json_data);
			return 0;
		}
		if(CGI_Beep_Control(dev_mac,beep_status?ZB_BEEP_ON:ZB_BEEP_OFF)==0)
			fprintf(cgiOut,success_json);
		else{
			error_printf(100,"CGI_Beep_Control",json_data);
			fprintf(cgiOut,json_data);
			return 0;
		}
		
	}else { //GET提交
		//获取灯的状态
		beep_status = CGI_Get_Beep_Status(dev_mac);
		if(beep_status!=-1){
			sprintf(json_data,success_json2,beep_status?"ON":"OFF");
			fprintf(cgiOut,json_data);
		}else{
			error_printf(100,"CGI_Get_Beep_Status",json_data); //传100是为了触发other error
			fprintf(cgiOut,json_data);
			return 0;
		}
		
		
		
	}
	
	
	return 0;
	
}

void error_printf(cgiFormResultType ret,char *str,char* out){
	char err_str[100];
	switch(ret){
		case cgiFormBadType:
			sprintf(err_str,"%s %s",str,"BadType");
			break;
		case cgiFormEmpty:
			sprintf(err_str,"%s %s",str,"Empty");
			break;
		case cgiFormNotFound:
			sprintf(err_str,"%s %s",str,"NotFound");
			break;
			
		default:
			//other error
			sprintf(err_str,"%s %s",str,"other error");
			break;
	}
	sprintf(out,faild_json,err_str);
}
